package cn.webrx.controller;


import cn.webrx.service.CaptchaService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseGifCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@RestController
public class CaptchaController {
    @Autowired
    CaptchaService cs;

    @GetMapping("/check")
    public Map<String, String> check() {
        Map<String, String> map = new HashMap<>();
        map.put("code", "200");
        map.put("msg", "验证码");
        //验证码key
        String checkkey = UUID.randomUUID().toString();
        map.put("checkkey", checkkey);

        Random rand = new Random();
        int num = rand.nextInt(1,5);
        //中文Gif动态验证码
        Captcha captcha = switch (num) {
            case 1 -> new ChineseGifCaptcha(130, 40);
            case 2 -> new SpecCaptcha(130, 40);
            case 3 -> new ArithmeticCaptcha(130, 40);
           default -> new GifCaptcha(130, 40);
        };
        int len = rand.nextInt(2,6);
        captcha.setLen(len);

        //验证码
        map.put("check", captcha.toBase64());

        //保存验证码的值
        String value = captcha.text();
        System.out.println(value);
        //checkkey captcha.text() redis缓存 mysql memory
        cn.webrx.entity.Captcha cc = new cn.webrx.entity.Captcha();
        cc.setId(checkkey);
        cc.setValue(value);
        cs.save(cc);
        return map;
    }
}
